/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.fty.web;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.jeesite.common.entity.DataScope;

import com.jeesite.common.mybatis.mapper.query.QueryType;
import com.jeesite.modules.BeanMapUtil;
import com.jeesite.modules.ChinaFontProvide;
import com.jeesite.modules.ChinaFontProvide1;
import com.jeesite.modules.Watermark;
import com.jeesite.modules.fty.entity.FtySelContract;
import com.jeesite.modules.sys.utils.EmpUtils;
import com.jeesite.modules.sys.utils.RmbUtil;
import com.jeesite.modules.sys.utils.UserUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.fty.entity.FtyLeaseContractFull;
import com.jeesite.modules.fty.service.FtyLeaseContractFullService;

import java.beans.IntrospectionException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * 合同表Controller
 * @author chensk
 * @version 2018-04-24
 */
@Controller
@RequestMapping(value = "${adminPath}/fty/ftyLeaseContractFull")
public class FtyLeaseContractFullController extends BaseController {

	@Autowired
	private FtyLeaseContractFullService ftyLeaseContractFullService;
	
	/**
	 * 获取数据
	 */
	@ModelAttribute
	public FtyLeaseContractFull get(String contractCode, boolean isNewRecord) {
		return ftyLeaseContractFullService.get(contractCode, isNewRecord);
	}
	
	/**
	 * 查询列表
	 */
	@RequiresPermissions("fty:ftyLeaseContractFull:view")
	@RequestMapping(value = {"list", ""})
	public String list(FtyLeaseContractFull ftyLeaseContractFull, Model model) {

		model.addAttribute("ftyLeaseContractFull", ftyLeaseContractFull);
		return "modules/fty/ftyLeaseContractFullList";
	}
	
	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("fty:ftyLeaseContractFull:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<FtyLeaseContractFull> listData(FtyLeaseContractFull ftyLeaseContractFull, HttpServletRequest request, HttpServletResponse response) {
		ftyLeaseContractFullService.addDataScopeFilter(ftyLeaseContractFull, null);
		if( UserUtils.getUser().getUserCode().equals("admin")){
			ftyLeaseContractFull.getSqlMap().getWhere().and("c_number", QueryType.IS_NOT_NULL, null);
		}
		Page<FtyLeaseContractFull> page = ftyLeaseContractFullService.findPage(new Page<FtyLeaseContractFull>(request, response), ftyLeaseContractFull);
		return page;
	}


	@RequestMapping(value = {"generalNumber"})
	@ResponseBody
	public String generalNumber(FtyLeaseContractFull ftyLeaseContractFull, Model model) {
		if(!ftyLeaseContractFull.getCreateBy().equals(EmpUtils.getEmployee().getEmpCode()))
			return renderResult(Global.FALSE, "您不是合同原件创建人,无法生成合同");
		if(StringUtils.isNotBlank(ftyLeaseContractFull.getCNumber()))
			return renderResult(Global.FALSE, "有序列号的合同已经生成,无法改变");
		ftyLeaseContractFullService.generalUUid(ftyLeaseContractFull);
		return renderResult(Global.TRUE, "生成合同编号成功！");
	}
	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("fty:ftyLeaseContractFull:view")
	@RequestMapping(value = "form")
	public String form(FtyLeaseContractFull ftyLeaseContractFull, Model model) {
		model.addAttribute("ftyLeaseContractFull", ftyLeaseContractFull);
		return "modules/fty/ftyLeaseContractFullForm";
	}

	/**
	 * 保存合同表
	 */
	@RequiresPermissions("fty:ftyLeaseContractFull:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated FtyLeaseContractFull ftyLeaseContractFull) {
		ftyLeaseContractFull.setCName(EmpUtils.getCompany().getFullName());
		ftyLeaseContractFull.setCLegal(EmpUtils.getCompany().getRepresentive());
		ftyLeaseContractFull.setCPEmail(EmpUtils.getCompany().getEmail());
		ftyLeaseContractFull.setCAddress(EmpUtils.getCompany().getOfficeAddress());
		ftyLeaseContractFull.setCPoscode(EmpUtils.getCompany().getZipcode());
		ftyLeaseContractFull.setBusinessNumber(EmpUtils.getCompany().getSnCode());
		ftyLeaseContractFull.setCPhone(EmpUtils.getCompany().getHeadTel());
		ftyLeaseContractFull.setRecordNumber(EmpUtils.getCompany().getRecordNum());
		ftyLeaseContractFull.setCPhone(EmpUtils.getCompany().getHeadTel());
		ftyLeaseContractFull.setCPName(EmpUtils.getEmployee().getEmpName());
		ftyLeaseContractFull.setCPPhone(EmpUtils.getEmployee().getTel());
		ftyLeaseContractFull.setCPIdcard(EmpUtils.getEmployee().getCardNo());
		ftyLeaseContractFull.setCompTel(EmpUtils.getCompany().getHeadTel());
		ftyLeaseContractFull.setCType("法定代表人");
		ftyLeaseContractFull.setCPServiceNumber(EmpUtils.getEmployee().getCertificate());
		ftyLeaseContractFullService.save(ftyLeaseContractFull);
		return renderResult(Global.TRUE, "保存合同表成功！");
	}
	
	/**
	 * 删除合同表
	 */
	@RequiresPermissions("fty:ftyLeaseContractFull:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(FtyLeaseContractFull ftyLeaseContractFull) {
		ftyLeaseContractFullService.delete(ftyLeaseContractFull);
		return renderResult(Global.TRUE, "删除合同表成功！");
	}



	@RequestMapping("/contract")
	public void sellercontract(FtyLeaseContractFull ftyLeaseContractFull, HttpServletRequest request,
							   HttpServletResponse response, HttpSession session)
			throws DocumentException, IOException, ParseException, IllegalAccessException, IntrospectionException, InvocationTargetException {
		//deposit_return_time drt
		//rent_advance rav
		//rent_change_time rct
		Map<String, Object> map = BeanMapUtil.bean2Map(ftyLeaseContractFull);

		response.setContentType("application/pdf");
		response.setHeader("Expires", "0");// 不缓存
		response.setHeader("Cache-Control",
				"must-revalidate, post-check=0, pre-check=0");
		response.setHeader("Pragma", "public");

		// 如果不想立即下载，屏蔽下面一行，就是浏览器中浏览了
		// response.setHeader("Content-disposition",
		// "attachment; filename = contract.pdf");
		String contract = Global.getConfig("sys.leasecontract.complex", "10");
		//contract  = contract.replaceAll("\\#"+"rav"+"\\#", );
		BaseFont bfChinese = BaseFont.createFont("STSongStd-Light",
				"UniGB-UCS2-H", false);
		Font fontBold = new Font(bfChinese, 25, Font.NORMAL);

		//要替换的字符名称
		String lender = "";
		try {
			Document document = new Document();
			ServletOutputStream out = response.getOutputStream();
			PdfWriter writer = PdfWriter.getInstance(document, out);// 输出到浏览器
//			print.setP
			writer.setPageEvent(new Watermark(ftyLeaseContractFull.getCNumber()));//水印内容 添加事件 在事件中添加水印
			// 若果是要输出到文件，取消下面的注释，屏蔽response的设置
			// PdfWriter writer = PdfWriter.getInstance(document,new
			// FileOutputStream("protocol.pdf"));
			document.addTitle("房屋租凭中介合同");// 仅仅是文档属性里的标题，不显示在页面
			document.open();
			//文字水印
			//添加水印和页码rct
			//contract = contract.replaceAll("\\#rct\\#",ftyLeaseContractFull.getRct());
			contract = contract.replaceAll("\\#rent_cn\\#", RmbUtil.number2CNMontrayUnit(new BigDecimal(StringUtils.isBlank(ftyLeaseContractFull.getRent())?"0":ftyLeaseContractFull.getRent()+"")));
			contract = contract.replaceAll("\\#inter_fee\\#", ftyLeaseContractFull.getServiceFee());
			contract = contract.replaceAll("\\#inter_fee_payer\\#", ftyLeaseContractFull.getServicePay());
			contract  = contract.replaceAll("\\#b_p_cardid\\#", StringUtils.isBlank(ftyLeaseContractFull.getBPCardId())?"/":ftyLeaseContractFull.getBPCardId());
			contract  = contract.replaceAll("\\#a_p_cardid\\#", StringUtils.isBlank(ftyLeaseContractFull.getAPCardId())?"/":ftyLeaseContractFull.getAPCardId());
			contract = contract.replaceAll("\\#drt\\#",ftyLeaseContractFull.getDepositReturnTime());
			InputStream cssStream = request.getServletContext().getResourceAsStream("/static/fang/style/word.css");
			contract = contract.replaceAll("\\#c_name_full\\#", ftyLeaseContractFull.getCName());
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
			contract = contract.replaceAll("\\#c_date\\#",format.format(ftyLeaseContractFull.getCreateDate()) );
			String contract1 = null;
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
			try {
				for (Map.Entry<String, Object> entry : map.entrySet()) {
					String key = entry.getKey().toLowerCase();
					Object value = entry.getValue();
					if(entry.getValue() instanceof Date){
						value = formatter.format(value);
					}
					contract  = contract.replaceAll("\\#"+key+"\\#", StringUtils.isBlank(value+"")?"/":String.valueOf(value));
				}
			}catch (Exception e){
				e.printStackTrace();
			}
			ByteArrayInputStream bin = new ByteArrayInputStream(contract.getBytes());
			XMLWorkerHelper.getInstance().parseXHtml(writer,document, bin,  cssStream, new ChinaFontProvide());
			document.close();
			out.close();
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}